/*
 * Copyright 2002-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.transaction.interceptor;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.springframework.lang.Nullable;

/**
 * TransactionAttribute implementation that works out whether a given exception
 * should cause transaction rollback by applying a number of rollback rules,
 * both positive and negative. If no custom rollback rules apply, this attribute
 * behaves like DefaultTransactionAttribute (rolling back on runtime exceptions).
 *
 * <p>{@link TransactionAttributeEditor} creates objects of this class.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @since 09.04.2003
 * @see TransactionAttributeEditor
 */
/*
1  类总结
	 基于规则的事务属性实现类
	扩展了 DefaultTransactionAttribute，支持自定义回滚规则
	通过正负回滚规则列表来决定异常是否触发事务回滚，提供了灵活的事务控制能力
2内部成员说明
	字段
		List<RollbackRuleAttribute> rollbackRules: 存储回滚规则列表，包含正向和负向规则
	构造函数
		public RuleBasedTransactionAttribute(): 创建新的基于规则的事务属性，默认设置
		public RuleBasedTransactionAttribute(RuleBasedTransactionAttribute other): 复制构造函数，复制另一个实例的配置
		public RuleBasedTransactionAttribute(int propagationBehavior, List<RollbackRuleAttribute> rollbackRules): 带传播行为和回滚规则的构造函数
	方法
		void setRollbackRules(List<RollbackRuleAttribute> rollbackRules): 设置回滚规则列表
		List<RollbackRuleAttribute> getRollbackRules(): 获取回滚规则列表
		boolean rollbackOn(Throwable ex): 判断是否应该对给定异常执行回滚操作，是核心逻辑方法
		String toString(): 返回事务属性的字符串表示，包含所有规则
3类关系结构
	TransactionDefinition (interface)	事务属性的顶层接口，定义了事务的基本特性，包含传播行为、隔离级别、超时时间等核心配置
	└── DefaultTransactionDefinition (class)	可修改的事务定义实现类，用于编程式事务管理，允许动态设置事务属性
	    ├── TransactionTemplate (class) 	Spring提供的编程式事务管理工具类，封装了事务的开始、提交和回滚逻辑，支持通过回调机制执行事务操作，简化事务管理代码，可以与 CallbackPreferringPlatformTransactionManager 配合使用
	    └── RuleBasedTransactionAttribute (class)	基于规则的事务属性实现，支持复杂的事务配置逻辑，用于处理带有条件判断的事务配置
	相关类和接口区别：
		TransactionDefinition: 事务属性的通用接口，定义基本事务特性
		TransactionAttribute: 在 TransactionDefinition 基础上扩展，支持AOP特有的回滚规则和限定符功能
		DefaultTransactionAttribute: 默认的事务属性实现，提供了基本的事务配置
		RuleBasedTransactionAttribute: 基于规则的事务属性实现，支持复杂的事务配置逻辑
4 使用场景
	需要自定义回滚规则的声明式事务管理
	实现复杂的事务控制逻辑，如基于条件的事务传播行为
	与AOP结合使用，实现细粒度的事务控制
	需要为事务添加标签以支持特定业务逻辑或监控需求
5 实际代码应用示例

// 使用TransactionTemplate实现编程式事务
@Autowired
private TransactionTemplate transactionTemplate;

public void updateUser(Long userId, String newName) {
    // 设置自定义事务属性
    RuleBasedTransactionAttribute attr = new RuleBasedTransactionAttribute();
    attr.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    attr.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);

    // 设置自定义回滚规则
    List<RollbackRuleAttribute> rules = new ArrayList<>();
    rules.add(new RollbackRuleAttribute(UserNotFoundException.class));
    attr.setRollbackRules(rules);

    // 执行事务
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            // 更新用户逻辑
            try {
                // 执行业务逻辑
            } catch (UserNotFoundException e) {
                // 根据自定义规则触发回滚
                status.setRollbackOnly();
            }
        }
    });

 */
@SuppressWarnings("serial")
public class RuleBasedTransactionAttribute extends DefaultTransactionAttribute implements Serializable {

	/** Prefix for rollback-on-exception rules in description strings. */
	public static final String PREFIX_ROLLBACK_RULE = "-";

	/** Prefix for commit-on-exception rules in description strings. */
	public static final String PREFIX_COMMIT_RULE = "+";


	@Nullable
	private List<RollbackRuleAttribute> rollbackRules;


	/**
	 * Create a new RuleBasedTransactionAttribute, with default settings.
	 * Can be modified through bean property setters.
	 * @see #setPropagationBehavior
	 * @see #setIsolationLevel
	 * @see #setTimeout
	 * @see #setReadOnly
	 * @see #setName
	 * @see #setRollbackRules
	 */
	public RuleBasedTransactionAttribute() {
		super();
	}

	/**
	 * Copy constructor. Definition can be modified through bean property setters.
	 * @see #setPropagationBehavior
	 * @see #setIsolationLevel
	 * @see #setTimeout
	 * @see #setReadOnly
	 * @see #setName
	 * @see #setRollbackRules
	 */
	public RuleBasedTransactionAttribute(RuleBasedTransactionAttribute other) {
		super(other);
		this.rollbackRules = (other.rollbackRules != null ? new ArrayList<>(other.rollbackRules) : null);
	}

	/**
	 * Create a new DefaultTransactionAttribute with the given
	 * propagation behavior. Can be modified through bean property setters.
	 * @param propagationBehavior one of the propagation constants in the
	 * TransactionDefinition interface
	 * @param rollbackRules the list of RollbackRuleAttributes to apply
	 * @see #setIsolationLevel
	 * @see #setTimeout
	 * @see #setReadOnly
	 */
	public RuleBasedTransactionAttribute(int propagationBehavior, List<RollbackRuleAttribute> rollbackRules) {
		super(propagationBehavior);
		this.rollbackRules = rollbackRules;
	}


	/**
	 * Set the list of {@code RollbackRuleAttribute} objects
	 * (and/or {@code NoRollbackRuleAttribute} objects) to apply.
	 * @see RollbackRuleAttribute
	 * @see NoRollbackRuleAttribute
	 */
	public void setRollbackRules(List<RollbackRuleAttribute> rollbackRules) {
		this.rollbackRules = rollbackRules;
	}

	/**
	 * Return the list of {@code RollbackRuleAttribute} objects
	 * (never {@code null}).
	 */
	public List<RollbackRuleAttribute> getRollbackRules() {
		if (this.rollbackRules == null) {
			this.rollbackRules = new ArrayList<>();
		}
		return this.rollbackRules;
	}


	/**
	 * Winning rule is the shallowest rule (that is, the closest in the
	 * inheritance hierarchy to the exception). If no rule applies (-1),
	 * return false.
	 * @see TransactionAttribute#rollbackOn(java.lang.Throwable)
	 */
	@Override
	public boolean rollbackOn(Throwable ex) {
		RollbackRuleAttribute winner = null;
		int deepest = Integer.MAX_VALUE;

		if (this.rollbackRules != null) {
			// 遍历所有的RollbackRuleAttribute，判断现在抛出的异常ex是否匹配RollbackRuleAttribute中指定的异常类型的子类或本身
			for (RollbackRuleAttribute rule : this.rollbackRules) {
				int depth = rule.getDepth(ex);
				if (depth >= 0 && depth < deepest) {
					deepest = depth;
					winner = rule;
				}
			}
		}

		// User superclass behavior (rollback on unchecked) if no rule matches.
		if (winner == null) {
			return super.rollbackOn(ex);
		}

		// ex所匹配的RollbackRuleAttribute，可能是NoRollbackRuleAttribute，如果是匹配的NoRollbackRuleAttribute，那就表示现在这个异常ex不用回滚
		//new RollbackRuleAttribute(IOException.class.getName())
		return !(winner instanceof NoRollbackRuleAttribute);
	}


	@Override
	public String toString() {
		StringBuilder result = getAttributeDescription();
		if (this.rollbackRules != null) {
			for (RollbackRuleAttribute rule : this.rollbackRules) {
				String sign = (rule instanceof NoRollbackRuleAttribute ? PREFIX_COMMIT_RULE : PREFIX_ROLLBACK_RULE);
				result.append(',').append(sign).append(rule.getExceptionName());
			}
		}
		return result.toString();
	}

}
